var express = require('express')
var app = express()
var bodyParser = require('body-parser');
var cookieParser = require('cookie-parser');
var session = require('express-session');
var manage = require("./router/manage")
var log = require("./router/log")
var raid = require("./router/raid")
var player = require("./router/player")

app.use(bodyParser.json({limit: '10mb'}));
app.use(bodyParser.urlencoded({limit: '10mb', extended: true}));
app.use(bodyParser.text({limit: '10mb'}));
app.use(cookieParser());
app.use(express.static(__dirname + '/public'));

app.use(session({
  secret: '12345',
  name: '',   //这里的name值得是cookie的name，默认cookie的name是：connect.sid
  cookie: {maxAge: 90000000 },  //设置maxAge，单位ms，即ms后session和相应的cookie失效过期
  resave: false,
  saveUninitialized: true,
}));

var noAuthPath = [//不需要登录的路由地址
  '/api/manage/login', //登录
  '/api/manage/loginCaptcha', //登录验证码
  '/api/manage/getBoardMsg', //获取公告信息
  '/api/log', 
  '/api/raid', 
  '/api/player'
].map(o=>o.toLowerCase())

app.use(function (req, res, next){
  if (!req.get('Origin')) return next();
  res.set('Access-Control-Allow-Origin', 'http://localhost:8001');
  res.set('Access-Control-Allow-Credentials', 'true');
  res.set('Access-Control-Allow-Methods', 'GET,POST');
  res.set('Access-Control-Allow-Headers', 'Authorization, X-Requested-With, Content-Type');
  if (req.method === 'OPTIONS') return res.send('200');
  next();
})

var {getUserByReq} = require('./data')
app.use(function (req, res, next) {
  var path = req.path.toLowerCase();
  if(path.startsWith('/api') && !getUserByReq(req) && req.method !== 'OPTIONS'){
  	if(noAuthPath.indexOf(path)<0 && !noAuthPath.some(o=>path.startsWith(o))){
  		return res.json({
        status: -3000,
        msg: '登录超时，请重新登录'
      });
  	}
  }
  next();
});

app.use('/api/manage', manage);
app.use('/api/log', log);
app.use('/api/raid', raid);
app.use('/api/player', player);


// var {adminDao,
//   logDao,
//   playerDao,
//   raidDao,
//   save
// } = require('./data')
// var moment = require('moment');
// const DT_FORMAT = 'YYYY-MM-DD HH:mm:ss'
// let dateFormat = function (dt) {
//   return moment(new Date(dt)).format(DT_FORMAT)
// }
// let fs = require('fs')
// let path = require('path')
// let file = '';
// file = fs.readFileSync(path.join(__dirname, 'mcdkp.json'), {
//   encoding: 'utf8'
// });
// let tmp = JSON.parse(file);
// let dkps = Object.keys(tmp).map(key=>({
//   name: key,
//   class: tmp[key].class,
//   race: '',
//   level: 60,
//   score: tmp[key].dkp_1
// })).filter(o=>o.score!=0)

// dkps.forEach(player=>{
//   if (!playerDao.exists(player.name)) {
//     playerDao.add({
//       ...player,
//       scores: {
//         MC: 0,
//         BWL: 0
//       },
//       joinTime: dateFormat(new Date)
//     })
//   }
// })
// let playerRelation = {}
// playerDao.playerRelation().forEach(o => {
//   playerRelation[o.name] = {
//     race: o.race,
//     class: o.class,
//     linkedTo: o.linkedTo
//   }
// })

// dkps.forEach(player=>{
//   let p = playerRelation[player.name];
//   if (!p.linkedTo) {
//     playerDao.changeScore([player.name], {
//       raid: '--',
//       scoreType: 'MC',
//       score: player.score,
//       reason: 'other',
//       reasonNote: '初次添加'
//     })
//   }
// })

app.listen(801);
console.log('服务已启动')